/*
 * @Author: duanguang
 * @Date: 2019-10-16 14:37:46
 * @LastEditTime: 2021-11-24 23:13:13
 * @LastEditors: duanguang
 * @Description: 
 * @FilePath: /legions-server/app/abstract/controller/decorators.ts
 * 「扫去窗上的尘埃，才可以看到窗外的美景。」
 */
import CommonController from './common';
import ResponseModel from '@/model/responseModel';
import { UserInfoEntity } from '@/model/user';
import { UserRoleEnum } from "@/constants/enum.types";
/**
 * 路由鉴权，路由配置需加上jwt中间件
 * eg: router.post('/sandbox/list', jwt as any, controller.sandbox.list)
 * @export
 * @param {UserRoleEnum} role 角色
 * @param {string} [message] 提示错误信息，默认：当前用户无权限操作
 * @returns
 */
export function roleAuthority(roleNo: UserRoleEnum, message?: string) {
    return (_: CommonController, __: string, descriptor: PropertyDescriptor) => {
        const oldValue = descriptor.value;
        descriptor.value = async function() {
            /** 执行方法之前执行鉴权操作 */
            // @ts-ignore
            const { ctx } = this;
            const userInfo: UserInfoEntity = ctx.state.user.userInfo;

            if (userInfo.roleNo < UserRoleEnum.admin) {
                if (userInfo.roleNo > roleNo) {
                    ctx.body = new ResponseModel({
                        success: false,
                        message: message || '当前用户无权限操作',
                    });
                    return;
                }
            } 
            return oldValue.apply(this, arguments);
        };
        return descriptor;
    };
}
